<?php

/**
 * SocialEngine
 *
 * @category   Application_Extensions 
 * @package    Communityad
 * @copyright  Copyright 2009-2011 BigStep Technologies Pvt. Ltd.
 * @license    http://www.socialengineaddons.com/license/
 * @version    $Id: Install.php  2011-02-16 9:40:21Z SocialEngineAddOns $
 * @author     SocialEngineAddOns
 */
class Communityad_Installer extends Engine_Package_Installer_Module {

  function onPreInstall() {
	$PRODUCT_TYPE = 'communityad';
	$PLUGIN_TITLE = 'Communityad';
	$PLUGIN_VERSION = '4.2.3';
	$PLUGIN_CATEGORY = 'plugin';
	$PRODUCT_DESCRIPTION = 'Communityad Plugin';
	$_PRODUCT_FINAL_FILE = 0;
	$_BASE_FILE_NAME = 0;
	$PRODUCT_TITLE = 'Advertisements / Community Ads Plugin';
	$SocialEngineAddOns_version = '4.2.3';
	$file_path = APPLICATION_PATH . "/application/modules/$PLUGIN_TITLE/controllers/license/ilicense.php";
	$is_file = file_exists($file_path);
	if (empty($is_file)) {
	  include_once APPLICATION_PATH . "/application/modules/$PLUGIN_TITLE/controllers/license/license3.php";
	} else {
	  if (!empty($_PRODUCT_FINAL_FILE)) {
		include_once APPLICATION_PATH . '/application/modules/' . $PLUGIN_TITLE . '/controllers/license/' . $_PRODUCT_FINAL_FILE;
	  }
	  $db = $this->getDb();
	  $select = new Zend_Db_Select($db);
	  $select->from('engine4_core_modules')->where('name = ?', $PRODUCT_TYPE);
	  $is_Mod = $select->query()->fetchObject();
	  if( empty($is_Mod) ) {
	    include_once $file_path;
	  }
	}
	parent::onPreInstall();
  }

  function onInstall() {

	$db = $this->getDb();

	$communityad_time_set = time();
	$select = new Zend_Db_Select($db);
	$select
			->from('engine4_core_modules')
			->where('name = ?', 'communityad');
	$modules_version = $select->query()->fetchObject();
	if (!empty($modules_version)) {
	  $product_version = $modules_version->version;

	  if ($product_version < '4.1.8p1') {
		$this->addWidgets();
	  }

	  // It is the script which delete all the unwanted row from the "like_table" which user has been deleted or not have existence on site.
	  if ($product_version < '4.1.9') {
		$this->deleteLikeTableRow();
	  }

	  if ($product_version == '4.1.2') {
		$table_exist = $db->query("SHOW TABLES LIKE 'engine4_communityad_package'")->fetch();
		if (!empty($table_exist)) {
		  $column_exist = $db->query("SHOW COLUMNS FROM engine4_communityad_package LIKE 'order'")->fetch();
		  if (empty($column_exist)) {
			$db->query("ALTER TABLE `engine4_communityad_package`  ADD `order` INT(11) NOT NULL DEFAULT '0'");
		  }

		  $column_level_exist = $db->query("SHOW COLUMNS FROM engine4_communityad_package LIKE 'level_id'")->fetch();
		  if (empty($column_level_exist)) {
			$db->query("ALTER TABLE `engine4_communityad_package`  ADD `level_id` VARCHAR(265) NOT NULL DEFAULT '0'");
		  }
		}
	  }
	}

	// check for ajax enabling column in table
	$table_page_exist = $db->query("SHOW TABLES LIKE 'engine4_communityad_pagesettings'")->fetch();
	if (!empty($table_page_exist)) {
	  $column_ajx_exist = $db->query("SHOW COLUMNS FROM engine4_communityad_pagesettings LIKE 'ajax_enabled'")->fetch();
	  if (empty($column_ajx_exist)) {
		$db->query("ALTER TABLE `engine4_communityad_pagesettings` ADD `ajax_enabled` BOOL NOT NULL DEFAULT '0' AFTER `value`");
	  }
	}

	$db->query("UPDATE  `engine4_seaocores` SET  `is_activate` =  '1' WHERE  `engine4_seaocores`.`module_name` ='communityad';");

	$db->query("INSERT IGNORE INTO `engine4_core_settings` (`name`, `value`) VALUES
		('communityad.base.time', $communityad_time_set ),
		('communityad.check.var', 0 ), 
		('communityad.time.var', 3456000 ),
		('communityad.get.path', 'Communityad/controllers/license/license2.php');");

	$db = $this->getDb();
	$select = new Zend_Db_Select($db);
	$select
			->from('engine4_core_settings')
			->where('name = ?', 'ad.block.width');
	$adWidthBlock = $select->query()->fetchObject();

	if ($adWidthBlock && $adWidthBlock->value != '150') {
	  $this->upgradeStyleCssFile($adWidthBlock->value);
	}

	// check for stats maintenance work
	if (!empty($modules_version) && $modules_version->version <= '4.1.6p1') {
	  $table_stats_exist = $db->query("SHOW TABLES LIKE 'engine4_communityad_adstatistics'")->fetch();
	  if (!empty($table_stats_exist)) {
		$db->query("ALTER TABLE `engine4_communityad_adstatistics` CHANGE `hostname` `hostname` VARCHAR( 60 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL , CHANGE `user_agent` `user_agent` VARCHAR( 500 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL , CHANGE `url` `url` VARCHAR( 1000 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL");

		$timeObj = new Zend_Date(time());
		$time_select = new Zend_Db_Select($db);
		$time_select
				->from('engine4_core_settings')
				->where('name = ?', 'core.locale.timezone');
		$time_setting = $time_select->query()->fetchObject();
		$timeObj->setTimezone($time_setting->value);

		$yesterday_time = $timeObj->getTimestamp() - 86400;
		$lastExecutedDate = gmdate('Y-m-d', $lastExecutedTime);
		$yesterday_date = gmdate('Y-m-d', $yesterday_time);

		$sub_status_select = new Zend_Db_Select($db);
		$sub_status_select
				->from('engine4_communityad_adstatistics', array('adstatistic_id', 'userad_id', 'adcampaign_id', 'response_date', 'SUM(value_click) as value_click', 'SUM(value_view) as value_view'))
				->where("DATE_FORMAT(response_date, '%Y-%m-%d') <= ?", $yesterday_date)
				->group("DATE_FORMAT(response_date, '%Y-%m-%d')")
				->group('userad_id');

		$yesterday_stats = $sub_status_select->query()->fetchAll();

		$db = Engine_Db_Table::getDefaultAdapter();
		$db->beginTransaction();

		try {

		  $stat_ids = array();
		  foreach ($yesterday_stats as $values) {
			$db->insert('engine4_communityad_adstatistics', array(
				'userad_id' => $values['userad_id'],
				'adcampaign_id' => $values['adcampaign_id'],
				'viewer_id' => 0,
				'hostname' => NULL,
				'user_agent' => NULL,
				'url' => NULL,
				'response_date' => $values['response_date'],
				'value_click' => $values['value_click'],
				'value_view' => $values['value_view'],
				'value_like' => 0,
			));
			$stat_ids[] = $db->lastInsertId('engine4_communityad_adstatistics');
		  }
		  $sub_string = (string) ("'" . join("', '", $stat_ids) . "'");

		  $query = "DELETE FROM `engine4_communityad_adstatistics` WHERE (DATE_FORMAT(`engine4_communityad_adstatistics`.`response_date`, " . "'%Y-%m-%d'" . ") <= '$yesterday_date') AND `engine4_communityad_adstatistics`.`adstatistic_id` NOT IN ($sub_string)";

		  $db->query($query);
		  $db->commit();
		} catch (Exception $e) {
		  $db->rollBack();
		  throw $e;
		}
	  }
	}

	$db->query("INSERT IGNORE INTO `engine4_core_tasks` (`title`, `module`, `plugin`, `timeout`, `processes`, `semaphore`, `started_last`, `started_count`, `completed_last`, `completed_count`, `failure_last`, `failure_count`, `success_last`, `success_count`) VALUES ('Ad Statistics Maintenance', 'communityad', 'Communityad_Plugin_Task_StatsMaintenance', '86400', '1', '0', '0', '0', '0', '0', '0', '0', '0', '0')");

	parent::onInstall();
  }

  // It is the script which delete all the unwanted row from the "like_table" which user has been deleted or not have existence on site.
  private function deleteLikeTableRow() {
	$db = $this->getDb();
	$getLike = $db->query('SELECT `like_id`, `poster_id` FROM  `engine4_communityad_likes`;')->fetchAll();
	foreach ($getLike as $getLikeValue) {
	  $getName = $db->query('SELECT `user_id` FROM  `engine4_users` WHERE  `user_id` = ' . $getLikeValue['poster_id'] . ' LIMIT 1')->fetchAll();
	  if (empty($getName)) {
		$db->query('DELETE FROM `engine4_communityad_likes` WHERE `engine4_communityad_likes`.`like_id` = ' . $getLikeValue['like_id'] . ' LIMIT 1');
	  }
	}
  }

  private function upgradeStyleCssFile($width) {
	$db = $this->getDb();
	$path = APPLICATION_PATH . '/application/modules/Communityad/externals/styles/style.css';
	@chmod($path, 0777);
	if (!@is_writeable($path)) {
	  //Engine_Api::_()->getApi('settings', 'core')->setSetting('ad.block.widthupdatefile', 0);
	  $db->query("UPDATE  `engine4_core_settings` SET  `engine4_core_settings`.`value` =  '0' WHERE  `engine4_core_settings`.`name` ='ad.block.widthupdatefile';");
	  return;
	}
	if (empty($width))
	  $width = 150;
	// Read the file in as an array of lines
	$fileData = file($path);
	$i = 0;
	$orignalWidth = $width;
	$newArray = null;

	foreach ($fileData as $key => $line) {


	  // find the line that starts with width: and change it to custome width
	  if (preg_match('/width:/', $line)) {

		if ($i == 1)
		  $width = ($orignalWidth + 10) * 3;
		if ($i == 4)
		  $width = ($orignalWidth + 20) * 5;
		if ($i == 7)
		  $width = ($orignalWidth + 20) * 4;

		$explode = explode(":", $line);
		$explode[1] = $width . 'px;' . "\n";
		$line = implode(":", $explode);

		$i++;
	  }

	  $newArray .= $line;
	}

	// Overwrite test.txt

	$fp = fopen($path, 'w');
	fwrite($fp, $newArray);
	@chmod($path, 0755);
	fclose($fp);
	// Engine_Api::_()->getApi('settings', 'core')->setSetting('ad.block.widthupdatefile', 1);
	$db->query("UPDATE  `engine4_core_settings` SET  `engine4_core_settings`.`value` =  '1' WHERE  `engine4_core_settings`.`name` ='ad.block.widthupdatefile';");
  }

  private function addWidgets() {

	$db = $this->getDb();

	// Add default widgets for "Sponsored Story" only for upgradation.
	$select = new Zend_Db_Select($db);
	$page_id = $select
					->from('engine4_core_pages', 'page_id')
					->where('name = ?', 'user_index_home')
					->limit(1)
					->query()
					->fetchColumn(0)
	;
	if (!empty($page_id)) {

	  // container_id (will always be there)
	  $select = new Zend_Db_Select($db);
	  $container_id = $select
					  ->from('engine4_core_content', 'content_id')
					  ->where('page_id = ?', $page_id)
					  ->where('type = ?', 'container')
					  ->where('name =?', 'main')
					  ->limit(1)
					  ->query()
					  ->fetchColumn()
	  ;

	  if (!empty($container_id)) {
		// middle_id (will always be there)
		$select = new Zend_Db_Select($db);
		$right_id = $select
						->from('engine4_core_content', 'content_id')
						->where('parent_content_id = ?', $container_id)
						->where('type = ?', 'container')
						->where('name = ?', 'right')
						->limit(1)
						->query()
						->fetchColumn()
		;

		// insert
		if ($right_id) {
		  $db->insert('engine4_core_content', array(
			  'page_id' => $page_id,
			  'type' => 'widget',
			  'name' => 'communityad.sponsored-stories',
			  'parent_content_id' => $right_id,
			  'order' => 999,
		  ));
		}
	  }
	}
  }

}